<template>
	<view class="container">
		<!-- 空白页 -->
		<view v-if="!hasLogin || empty===true" class="empty">
			<!-- <image src="/static/emptyCart.jpg" mode="aspectFit"></image> -->
            <view class="this-background-img">
                <image ></image>
            </view>
			<view v-if="hasLogin" class="empty-tips ">

				<!-- Nothing at all -->
                Oops, Your Order Cart is Empty <br />
                Browser our awesome services now!
                
				<navigator class="navigator" v-if="hasLogin" url="../index/index" open-type="switchTab">Start Discover</navigator>
			</view>
			<view v-else class="empty-tips">
				<!-- Nothing at all -->
				<!-- <view class="navigator" @click="navToLogin">Go to login></view> -->
                Oops, Your Order Cart is Empty <br />
                Browser our awesome services now!
                
                <navigator class="navigator" @click="navToLogin">Go to login</navigator>
			</view>
		</view>
		<view v-else>
			<!-- 列表 -->
			<view class="cart-warpper" v-for="(item, index) in cartList" :key="item.id">
				<block>
					<view class="cart-item">
						<text class="tit">{{item.goods_name}}</text>
						<text class="red-price">${{item.goods_price}}/Unite</text>
						<view class="edit-item">
							<image mode="aspectFit" src="/static/images/delete.png" @click="delCart(item.id)"></image>
							<image mode="aspectFit" src="/static/images/edit-button.png" @click="editCart(item.id)"></image>
							<text @click="editCart(item.id)">Notes</text>
							<uni-number-box 
								class="step"
								:min="1" 
								:max="100"
								:value="item.goods_num"
								@change="numberChange($event,index)"
							></uni-number-box>
						</view>
					</view>
				</block>
			</view>
			<!-- 底部菜单栏 -->
			<view class="footer">
				<text class="total-tit">Total :<text class="red-price">${{total}}</text></text>
				<button class="add-btn" @click="goCheckOut">Check Out</button>
			</view>
		</view>
	</view>
</template>

<script>
	import uniNumberBox from '@/components/uni-number-box/uni-number-box.vue'
	export default {
		components: {
			uniNumberBox
		},
		data() {
			return {
				total: 0, //总价格
				allChecked: false, //全选状态  true|false
				empty: false, //空白页现实  true|false
				cartList: [],
				hasLogin: false
			};
		},
		onShow(){
			this.loadData();
			this.hasLogin = this.$db.get('userToken') || false;
		},
		watch:{
			//显示空白页
			cartList(e){
				let empty = e.length === 0 ? true: false;
				if(this.empty !== empty){
					this.empty = empty;
				}
			}
		},
		methods: {
			//请求数据
			async loadData(){
				this.$api.cartList(res => {
					if(res.code === 1) {
						this.cartList = res.data.map(item=>{
							item.checked = true;
							return item;
						});
						this.calcTotal();
					}
				})
				
				// let list = await this.$api.json('cartList');
				// let cartList = list.map(item=>{
				// 	item.checked = true;
				// 	return item;
				// });
				this.calcTotal();  //计算总价
			},
			//监听image加载完成
			onImageLoad(key, index) {
				this.$set(this[key][index], 'loaded', 'loaded');
			},
			//监听image加载失败
			onImageError(key, index) {
				this[key][index].image = '/static/errorImage.jpg';
			},
			navToLogin(){
				uni.navigateTo({
					url: '/pages/public/login'
				})
			},
			 //选中状态处理
			check(type, index){
				if(type === 'item'){
					this.cartList[index].checked = !this.cartList[index].checked;
				}else{
					const checked = !this.allChecked
					const list = this.cartList;
					list.forEach(item=>{
						item.checked = checked;
					})
					this.allChecked = checked;
				}
				this.calcTotal(type);
			},
			//数量
			numberChange(val, index){
				console.log(val)
				let num = parseInt(val.newVal) - parseInt(val.oldVal)
				if(num === 0) {
					return;
				}
				let data = {
					id: this.cartList[index].id,
					goods_num: Math.abs(num)
				}
				let _this = this
				if(num > 0) {
					this.$api.cartIncrease(data, res => {
						_this.cartList[index].goods_num = parseInt(val.newVal);
						_this.calcTotal();
					})
				} else {
					this.$api.cartDecrease(data, res => {
						_this.cartList[index].goods_num = parseInt(val.newVal);
						_this.calcTotal();
					})
				}
			},
			//删除
			deleteCartItem(index){
				let list = this.cartList;
				let row = list[index];
				let id = row.id;

				this.cartList.splice(index, 1);
				this.calcTotal();
				uni.hideLoading();
			},
			//清空
			clearCart(){
				uni.showModal({
					content: 'Clear Cart？',
					success: (e)=>{
						if(e.confirm){
							this.cartList = [];
						}
					}
				})
			},
			//计算总价
			calcTotal(){
				let list = this.cartList;
				if(list.length === 0){
					this.empty = true;
					return;
				}
				let total = 0;
				let checked = true;
				list.forEach(item=>{
					if(item.checked === true){
						// 是否有额外的价格，如果有就从第二个开始按照额外价格计算
						if(item.goods_extra_price && parseFloat(item.goods_extra_price) > 0) {
							if(item.goods_num > 1) {
								total += (item.goods_num - 1) * parseFloat(item.goods_extra_price) + parseFloat(item.goods_price)
							} else {
								total += parseFloat(item.goods_price)
							}
						} else {
							total += parseFloat(item.goods_price) * item.goods_num
						}
					}else if(checked === true){
						checked = false;
					}
				})
				console.log(total)
				this.allChecked = checked;
				this.total = Number(total.toFixed(2));
			},
			//创建订单
			createOrder(){
				let list = this.cartList;
				let goodsData = [];
				list.forEach(item=>{
					if(item.checked){
						goodsData.push({
							attr_val: item.attr_val,
							number: item.number
						})
					}
				})

				uni.navigateTo({
					url: `/pages/order/createOrder?data=${JSON.stringify({
						goodsData: goodsData
					})}`
				})
				this.$api.msg('Order create successfully!');
			},
			// 跳转到结算界面
			goCheckOut() {
				if(this.cartList.length <= 0) {
					this.$common.errorToShow('There is nothing to settle')
					return
				}
				let cart_ids = this.cartList.map(item => item.id).join(',')
				this.$common.navigateTo('../checkout/checkout?cart=' + cart_ids)
			},
			delCart(id) {
				let _this = this
				let data = {
					id: id
				}
				this.$common.modelShow('Tips', 'Are you sure you want to delete', ()=> {
					_this.$api.cartDel(data, res=> {
						if(res.code === 1) {
							_this.$common.successToShow('Successfully Deleted', ress => {
								_this.loadData();
							})
						} else {
							_this.$common.errorToShow(res.msg)
						}
					})
				})
			},
			editCart(id) {
				this.$common.navigateTo('../category/services?cart_id=' + id)
			}
		}
	}
</script>

<style lang='scss' scoped>
	.container{
		padding-bottom: 134upx;
		/* 空白页 */
		.empty{
            vertical-align: middle;
			position:fixed;
			left: 0;
			top: 20vh;
			width: 100%;
			height: 60vh;
			padding-bottom:100upx;
			display:flex;
			justify-content: center;
			flex-direction: column;
			align-items:center;
			background: #fff;
			/* image{
				width: 240upx;
				height: 160upx;
				margin-bottom:30upx;
			} */
			.empty-tips{
				display:flex;
				font-size: $font-sm+10upx;
				color: $font-color-disabled;
				.navigator{
					/* color: $uni-color-primary;
					margin-left: 16upx; */
                    
                    text-align: center;
                    vertical-align: middle;
                    
                    position: fixed;
                    left: 30upx;
                    right: 30upx;
                    bottom: 180upx;
                    z-index: 95;
                    width: 700upx;
                    height: 80upx;
                    line-height: 80upx;
                    border-radius: 10rpx;
                    background: #4666D5;
                    color: #fff;
                    font-family: Poppins;
                    font-size: $font-base;
                    font-weight: bold;
                    box-shadow: 0 20rpx 60rpx rgba(64, 191, 255, 0.24);
				}
			}
            .this-background-img {
                background: url('/static/images/cart.jpg') center center no-repeat;
                background-size: 60% auto;
                /* width: 100%; */
                vertical-align: middle;
                display: inline-block;
            }
		}
	}
	/* 购物车内容 */
	.cart-warpper {
		padding: 32rpx;
		.cart-item {
			display: flex;
			flex-direction: column;
			border: 2rpx solid #EBF0FF;
			box-sizing: border-box;
			border-radius: 10rpx;
			position:relative;
			padding:30upx 40upx;
			.tit {
				font-weight: bold;
				font-size: $font-base;
				line-height: 48rpx;
				color: #223263;
				margin-bottom: 16rpx;
			}
			.red-price {
				font-family: Poppins;
				font-weight: bold;
				font-size: $font-base;
				letter-spacing: 1rpx;
				line-height: 150%;
				color: #F64B15;
				margin-bottom: 12rpx;
			}
			.edit-item {
				display: flex;
				flex-direction: row;
				justify-content: flex-start;
				align-items: center;
				image {
					width: 40rpx;
					height: 40rpx;
					margin-right: 12rpx;
				}
				text {
					font-size: $font-base;
					color: #82858F;
				}
				.step {
					position: absolute;
					right: 20rpx;
				}
			}
		}
	}
	.footer {
		padding-top: 10rpx;
		justify-content: space-between;
		align-items: center;
		.total-tit {
			flex: 1;
			font-size: $font-base;
			line-height: 150%;
			font-weight: bold;
			color: #223263;
			text {
				margin-left: 26rpx;
			}
		}
	}
</style>
